package com.lengxf.mybatis.test;

import cn.hutool.core.collection.CollectionUtil;
import com.lengxf.mybatis.generate.ColumnGenerate;
import com.lengxf.mybatis.generate.TableInfo;
import com.lengxf.mybatis.mysql.mapper.TableMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TableService {

    private final TableMapper tableMapper;


    public void generateTable(List<TableInfo> list) {
        Map<String, List<TableInfo>> table = list.stream()
                .collect(Collectors.groupingBy(TableInfo::getTableName, Collectors.toList()));

        System.out.println("分组完成");

        for (Map.Entry<String, List<TableInfo>> entry : table.entrySet()) {
            String tableName = ("`" + entry.getKey() + "`").toLowerCase();
            List<TableInfo> value = entry.getValue();
            String tableComment = value.get(0).getTableComment();
            tableComment  = StringUtils.isBlank(tableComment) ? tableName : tableComment;
            String finalTableComment = "'" + tableComment  + "'";
            List<String> columnSqlList = value.stream().map(ColumnGenerate::generate)
                    .filter(Objects::nonNull)
                    .toList();
            if (CollectionUtil.isEmpty(columnSqlList)) {
                System.out.println(tableName + " 表不存在列, 已经跳过创建步骤");
                continue;
            }
            List<String> allColumnSqlList = joinColumnSql(columnSqlList);
            tableMapper.dropTable(tableName);
            tableMapper.generateTable(tableName, finalTableComment, allColumnSqlList);
            System.out.println(tableName + "建表语句执行完毕..");
        }
    }

    private List<String> joinColumnSql(List<String> columnSqlList) {
        String id = "`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键'";
        List<String> resultList = new ArrayList<>();
        List<String> idList = List.of(id);
        List<String> common = List.of("`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'",
                "`create_by` varchar(32) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '创建人'",
                "`update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间'",
                "`update_by` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '修改人'");
        resultList.addAll(idList);
        resultList.addAll(columnSqlList);
        resultList.addAll(common);
        return resultList;
    }

}
